import XIAOFEI_IM, { APP_PLATFORM, APP_VERSION, generateUUID, getBrowser, urlParamsAssemble } from "./xiaofei-im-utils";
// 服务器IP
const XIAOFEI_IM_HOST = "127.0.0.1";
// 服务端 websocket端口
const XIAOFEI_IM_PORT = 8002;
// URL
const XIAOFEI_IM_URL = "ws://" + XIAOFEI_IM_HOST + ":" + XIAOFEI_IM_PORT + "/ws";


export const createSocket = (url = XIAOFEI_IM_URL, authPayLoad) => {
    const deviceId = generateUUID();
    const browser = getBrowser();
    const params = {
        deviceId: deviceId,
        ip: authPayLoad.ip,
        version: APP_VERSION,
        platform: APP_PLATFORM,
        token: authPayLoad.token,
        address: authPayLoad.address,
        osVersion: browser.version,
        deviceName: browser.name,
        language: authPayLoad.language
    };
    const socketTask = uni.connectSocket({
		url: encodeURI(urlParamsAssemble(url, params)),
        header: {
            ...params
        },
		success(data) {
			console.log("success",data);
		},
		fail: (err) => {
			console.log("报错",err);
		}
	});
    socketTask.onOpen(() => XIAOFEI_IM.onOpen);
    socketTask.onClose(() => XIAOFEI_IM.onClose);
    socketTask.onError(() => XIAOFEI_IM.onClose);
    XIAOFEI_IM.createSocket = () => {
        createSocket(url, authPayLoad);
    };
    socketTask.onMessage(res => {
        XIAOFEI_IM.onMessage(res.data)
    });
    XIAOFEI_IM.socketTask = socketTask;
    return XIAOFEI_IM;
}

